import React, {useEffect, useState} from 'react';
import {Button, Card, Checkbox, Col, Divider, Form, type FormProps, Image, Input, message, Modal, Row} from 'antd';
import {FieldTimeOutlined, TeamOutlined, UserOutlined, VerifiedOutlined} from '@ant-design/icons';

import UploadAvatarTest from "@/components/UpdateAvatarInfo";
import TextArea from "antd/es/input/TextArea";
import {getInitialState} from "@/app";
import {useModel} from "@@/exports";
import {
  emailCodeUsingGet,
  getLoginUserUsingGet,
  updateMyUserUsingPost,
  userLoginByEmailUsingPost1
} from "@/services/backend/userController";

const Info: React.FC = () => {

  type FieldType = {
    email?: string;
    userPassword?: string;
    code?: string;
    checkPassword?: string;
  };

  const [loading, setLoading] = useState(true);

  const [componentDisabled, setComponentDisabled] = useState<boolean>(false);
  const [formDisabled, setFormDisabled] = useState<boolean>(false);
  const [userInfo, setUserInfo] = useState<API.UserVO>();
  const [codeButtonDisabled, setCodeButtonDisabled] = useState(false);
  // @ts-ignore
  const {initialState, setInitialState} = useModel('@@initialState');

  const [form] = Form.useForm();
  const [pform] = Form.useForm();

  const getUserInfo = async () => {
    const res = await getLoginUserUsingGet();
    if (res.code === 0) {
      setUserInfo(res.data)
      setLoading(false)
    } else {
      // message.error("信息获取失败-" + res.message)
      setLoading(false)
    }

  }

  // 进入页面获取数据
  useEffect(() => {
    getUserInfo()
  }, [])


  const refreshPage = () => {
    getUserInfo()
  };

  /**
   * 修改个人信息
   * @param values
   */
  const updateMyInfo = async (values: API.UserUpdateMyRequest) => {
    const res = await updateMyUserUsingPost(values);
    if (res.code === 0) {
      setLoading(false)
      message.success("信息修改成功")
      // 刷新页面
      await getUserInfo()
      // 重新获取用户信息
      const newUserInfo = await getInitialState();
      setInitialState(newUserInfo);
      setComponentDisabled(false)
    } /*else {
      message.error("信息修改失败-" + res.message)
      setLoading(false)
    }*/
    setLoading(false)
  }

  // 修改密码
  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    try {
      const res = await userLoginByEmailUsingPost1(values);
      if (res.code === 0) {
        message.success("修改成功")
        setFormDisabled(false)
      } /*else {
        message.error("修改失败-" + res.message)
        setFormDisabled(false)
      }*/
      setFormDisabled(false)
    } catch (e) {
      message.error("修改失败-" + e)
      setFormDisabled(false)
    }
  };

  //改变发送验证码按钮状态
  const handleGetCode = async () => {
    if (codeButtonDisabled) return;

    // 禁用按钮
    setCodeButtonDisabled(true);

    // 发送验证码
    const res = await emailCodeUsingGet({email: pform.getFieldValue('email')});
    if (res.code === 0) {
      message.success("验证码已发送，3分钟有效")
    } /*else {
      message.error("验证码发送失败-" + res.message)
    }*/

    // 设置一分钟后重新启用按钮
    setTimeout(() => {
      setCodeButtonDisabled(false);
    }, 60000);
  }

  return (
    <div style={{
      marginTop: '10px'
    }}>
      <Row gutter={[16, 16]}>
        <Col xs={24} md={6}>
          <Card title="个人信息" loading={loading}>
            <div style={{
              textAlign: 'center'
            }}>
              <Card>
                <Image
                  width={100}
                  /*style={{
                    borderRadius: '50%',
                  }}*/
                  src={userInfo?.userAvatar}
                />
                <br/>
                <UploadAvatarTest userInfo={userInfo} onRefresh={refreshPage}/>
              </Card>
            </div>
            <Divider/>
            <p><UserOutlined/>&nbsp;用户账号：{userInfo?.userAccount}</p>
            <Divider/>
            <p><TeamOutlined/>&nbsp;用户昵称：{userInfo?.userName}</p>
            <Divider/>
            <p><VerifiedOutlined/>&nbsp;用户角色：{userInfo?.userRole}</p>
            <Divider/>
            <p><FieldTimeOutlined/>&nbsp;注册时间：{userInfo?.createTime}</p>
          </Card>
        </Col>
        <Col xs={24} md={18}>
          <Card>
            <>
              <Checkbox checked={componentDisabled} onChange={e => setComponentDisabled(e.target.checked)}>
                修改
              </Checkbox>
              <Form
                labelCol={{span: 4}}
                wrapperCol={{span: 14}}
                layout="horizontal"
                // onValuesChange={onFormLayoutChange}
                disabled={!componentDisabled}
                onFinish={async (values) => {
                  await updateMyInfo(values as API.UserUpdateMyRequest);
                }}
                form={form}
                initialValues={userInfo}
              >
                <Form.Item label="账号" name="userAccount">
                  <Input placeholder={userInfo?.userAccount} name="userAccount"/>
                </Form.Item>
                <Form.Item label="昵称" name="userName">
                  <Input placeholder={userInfo?.userName} name="userName"/>
                </Form.Item>
                <Form.Item label="手机号" name="phone">
                  <Input placeholder={userInfo?.phone} name="phone"/>
                </Form.Item>
                <Form.Item label="邮箱" name="email">
                  <Input placeholder={userInfo?.email} name="email"/>
                </Form.Item>
                <Form.Item label="个人简介" name="userProfile">
                  <TextArea rows={4} placeholder={userInfo?.userProfile} name="userProfile"/>
                </Form.Item>
                <Form.Item wrapperCol={{span: 14, offset: 4}}>
                  <Row gutter={[10, 10]} justify="space-between" align="middle">
                    <Col span={7}>
                      <Button type="primary" htmlType="submit">修改信息</Button>
                    </Col>
                    <Col span={7} offset={2} xs={12}>
                      <Button danger onClick={() => setFormDisabled(true)}>修改密码</Button>
                    </Col>
                  </Row>
                </Form.Item>
              </Form>
            </>
          </Card>
        </Col>
      </Row>

      <Modal
        visible={formDisabled}
        onCancel={() => {
          setFormDisabled(false);
        }}>
        <Form
          style={{marginTop: '20px'}}
          name="basic"
          form={pform}
          onFinish={onFinish}
        >
          <Form.Item<FieldType>
            label="邮箱"
            name="email"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            rules={[{
              required: true,
              message: '邮箱是必填项！',
            },
              {
                pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/,
                message: '不合法的邮箱！',
              },]}
          >
            <Input/>
          </Form.Item>

          <Form.Item
            label="验证码"
            name="code"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            rules={[{required: true, message: '请输入验证码!'}]}
          >
            <Row gutter={8}>
              <Col span={16}>
                <Input
                  placeholder="请输入验证码"
                />
              </Col>
              <Col span={8}>
                <Button onClick={handleGetCode} type="primary" disabled={codeButtonDisabled}>
                  获取验证码
                </Button>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item<FieldType>
            label="新密码"
            name="userPassword"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            rules={[{required: true, message: '请输入密码!'}]}
          >
            <Input.Password/>
          </Form.Item>

          <Form.Item<FieldType>
            label="确认密码"
            name="checkPassword"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            rules={[{required: true, message: '请输入确认密码!'}]}
          >
            <Input.Password/>
          </Form.Item>

          <Form.Item wrapperCol={{offset: 8, span: 16}}>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Info;
